<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🔍 权限问题调试测试</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            border-bottom: 3px solid #4CAF50;
            padding-bottom: 10px;
        }
        h2 {
            color: #555;
            margin-top: 0;
        }
        .input-group {
            margin: 15px 0;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #666;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-family: monospace;
        }
        button {
            background: #4CAF50;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
            font-size: 14px;
        }
        button:hover {
            background: #45a049;
        }
        button:active {
            background: #3d8b40;
        }
        .result, .logs {
            margin-top: 20px;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 13px;
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
        }
        .success { color: #4CAF50; font-weight: bold; }
        .error { color: #f44336; font-weight: bold; }
        .info { color: #2196F3; }
        .warning { color: #ff9800; }
        .test-button-group {
            margin: 20px 0;
        }
        .step {
            background: #e3f2fd;
            padding: 10px;
            margin: 10px 0;
            border-left: 4px solid #2196F3;
            border-radius: 4px;
        }
        .success-box {
            background: #e8f5e9;
            padding: 10px;
            margin: 10px 0;
            border-left: 4px solid #4CAF50;
            border-radius: 4px;
        }
        .error-box {
            background: #ffebee;
            padding: 10px;
            margin: 10px 0;
            border-left: 4px solid #f44336;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 客户权限问题调试测试</h1>

        <div class="success-box">
            <strong>✅ 修复内容：</strong>
            <ul>
                <li>已启用<code>creator</code>（录入人）权限检查</li>
                <li>已添加详细的调试日志</li>
                <li>数据库中客户ID 1671和1673的<code>admin_id</code>字段为1</li>
            </ul>
        </div>

        <div class="step">
            <strong>步骤1：</strong> 在前端登录系统 → F12 → Console → 输入 <code>localStorage.getItem('token')</code> → 复制Token
        </div>

        <div class="input-group">
            <label>Token（必填）：</label>
            <textarea id="tokenInput" rows="3" placeholder="粘贴你的token..."></textarea>
        </div>

        <div class="input-group">
            <label>客户ID（可以输入多个，用逗号分隔）：</label>
            <input type="text" id="customerIdInput" value="1671,1673,1675" placeholder="例如：1671,1673">
            <small style="color: #999;">
                💡 已知客户：1671(admin_id=1), 1673(admin_id=1), 1675(admin_id=1) - 都是liuhui录入的客户
            </small>
        </div>

        <div class="test-button-group">
            <button onclick="testAccess()">🧪 测试权限检查</button>
            <button onclick="clearResults()">🗑️ 清空结果</button>
        </div>

        <div class="result" id="result">请输入Token和客户ID，然后点击"测试权限检查"按钮...</div>
        <div class="logs" id="logs"></div>
    </div>

    <script>
        function getToken() {
            return document.getElementById('tokenInput').value.trim();
        }

        function getCustomerIds() {
            const input = document.getElementById('customerIdInput').value.trim();
            if (!input) return ['1671'];
            return input.split(',').map(id => id.trim()).filter(id => id);
        }

        function addLog(message, type = 'info') {
            const logsDiv = document.getElementById('logs');
            const timestamp = new Date().toLocaleTimeString();
            const className = type;
            logsDiv.innerHTML += `[${timestamp}] <span class="${className}">${message}</span>\n`;
            logsDiv.scrollTop = logsDiv.scrollHeight;
        }

        function clearResults() {
            document.getElementById('result').textContent = '已清空，请重新测试...';
            document.getElementById('logs').textContent = '';
        }

        async function testAccess() {
            const token = getToken();
            const customerIds = getCustomerIds();
            const resultDiv = document.getElementById('result');

            if (!token) {
                resultDiv.innerHTML = '<span class="error">❌ 请先输入Token</span>';
                return;
            }

            resultDiv.textContent = `正在测试 ${customerIds.length} 个客户ID的权限检查...\n\n`;
            addLog('=== 开始权限检查测试 ===', 'info');
            addLog(`客户IDs: ${customerIds.join(', ')}`, 'info');
            addLog(`Token: ${token.substring(0, 20)}...`, 'info');

            let allSuccess = true;
            let results = [];

            for (const customerId of customerIds) {
                const url = `http://127.0.0.1:8000/api/customer/customer/view?id=${customerId}`;

                try {
                    addLog(`\n--- 测试客户ID: ${customerId} ---`, 'info');
                    addLog(`请求URL: ${url}`, 'info');

                    const response = await fetch(url, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + token
                        }
                    });

                    const data = await response.json();
                    const status = response.status;

                    if (status === 200) {
                        addLog(`✅ 客户ID ${customerId}: 200 OK - 权限检查通过！`, 'success');
                        results.push({ id: customerId, status: 'success', name: data.data?.name });
                    } else if (status === 403) {
                        addLog(`❌ 客户ID ${customerId}: 403 Forbidden - 权限不足`, 'error');
                        results.push({ id: customerId, status: 'failed', error: '无权访问' });
                        allSuccess = false;
                    } else if (status === 401) {
                        addLog(`⚠️ 客户ID ${customerId}: 401 Unauthorized - Token无效`, 'warning');
                        results.push({ id: customerId, status: 'failed', error: 'Token无效' });
                        allSuccess = false;
                    } else {
                        addLog(`❌ 客户ID ${customerId}: ${status} - 测试失败`, 'error');
                        results.push({ id: customerId, status: 'failed', error: status });
                        allSuccess = false;
                    }
                } catch (error) {
                    addLog(`❌ 客户ID ${customerId}: 错误 - ${error.message}`, 'error');
                    results.push({ id: customerId, status: 'failed', error: error.message });
                    allSuccess = false;
                }
            }

            // 显示总结结果
            resultDiv.textContent += '\n========== 测试结果总结 ==========\n';
            results.forEach(r => {
                const icon = r.status === 'success' ? '✅' : '❌';
                const text = r.status === 'success'
                    ? `客户${r.id}: 成功 - ${r.name || 'N/A'}`
                    : `客户${r.id}: 失败 - ${r.error}`;
                resultDiv.textContent += `${icon} ${text}\n`;
            });

            if (allSuccess) {
                resultDiv.innerHTML += '\n\n🎉 所有客户权限检查都通过！权限问题已解决。';
            } else {
                resultDiv.innerHTML += '\n\n⚠️ 存在权限问题，请查看下方详细日志。';
            }

            addLog('\n=== 测试完成 ===', 'info');
        }
    </script>
</body>
</html>
